eval 'exec perl -wS $0 ${1+"$@"}'
 if 0;

use strict;
use warnings;
use POSIX qw(strftime);

use DBI();
use File::Basename;
use File::stat;
use Data::Dumper 'Dumper';

use IO::Socket;

sub print_h_content
{
    my $hash=shift @_;
    
    foreach my $thekey (keys %$hash)
    {
	print $thekey." => ".$hash->{$thekey}."\n";
    }
}

sub slsecd_connect
{
    my $socket=shift @_;
    my $proto=shift @_;
    my $peeraddr=shift @_;
    my $peerport=shift @_;
    
    $$socket=IO::Socket::INET->new( Proto     => $$proto,
				      PeerAddr  => $$peeraddr,
				      PeerPort  => $$peerport
				      );
    unless ($$socket)
    {
	return 0;
    }
    return 1;
}

sub slsecd_disconnect
{
    my $socket=shift @_;
    
    close $$socket;
}

sub get_deciphered_data
{
    my $imei = shift @_;
    my $data = shift @_;
    my $res;
    my $socket=0;
    my $proto="tcp";
    #my $peeraddr="172.24.61.137";
    my $peeraddr="127.0.0.1";
    my $peerport="30000";

    #print ">get_deciphered_data<";
    if (! slsecd_connect(\$socket,\$proto,\$peeraddr,\$peerport))
    {
	error("Failed to connect to slsecd.\n");
	return 4;
    }
    #print { $h_ref_param->{SOCKET} } "D;" .$thekey. ";" .$h_ref_enciphered_keys->{$thekey}. "\n";
    print $socket "D;" .$imei. ";" .$data. "\n";
    
    $res = <$socket>;
    print $res;
    
    print $socket "Q\n";
    if (! slsecd_disconnect(\$socket))
    {
	warning("Failed to disconnect from slsecd.\n");
    }
    
    return 1;
}

my $arg="";
my $imei;
my $data;

#warn Dumper(@ARGV);
if (! defined $ARGV[1])
{
    print "[ERROR] Missing arguments. Aborting...\n";
    exit;
}

while ($arg=shift @ARGV)
{
    chomp($arg);
    if (! defined $imei)
    {
	$imei=$arg;
    }
    elsif (! defined $data)
    {
	$data=$arg;
    }
}


#print ">".$imei."<\n";
#print ">".$data."<\n";

get_deciphered_data($imei,$data);
#get_deciphered_data("332021536074029","962A47E6A26C7059F9FB5987DA01B8B17CDBA43446EFC3599FE19EF3D940B417D49093A4");
